<script lang="ts" setup>
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { reactive, ref } from 'vue'
import { GetBgUrl, GetData, GetExcelData, PostAlterBgUrl, PostCopy, deleteCoupon, patchListType } from '@/api/modules/voucher.ts'
import { PostUpdateTime } from '@/api/modules/subscribercouponpackage.ts'
// import PageNumber from '@/store/modules/PageNumberCache'
import storage from '@/utils/storage'
import GetCacheData from '@/store/modules/NewPageCache'

// const PageNumberCache = PageNumber()
const router = useRouter()
const imgDomain = 'https://img1.eprhan.cc'
const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('voucher').currentPage

// 查询表单
const findFrom = reactive({
  ...(cacheData.GetCacheData('voucher').fromData),
  Time: [],
})
const voucherType = [
  { label: '赠品券', value: '1' },
  { label: '奖品券', value: '2' },
  { label: '满减券', value: '3' },
]
const voucherFlag = [
  { label: '使用中', value: 1 },
  { label: '已停用', value: 0 },
]
// 加载
const loading = ref(false)
const total = ref(0) // 总数据数

// 数据列表
const dataList = reactive({
  list: [],
  urlList: [],
})
const bgUrlList = ref<string[]>([])

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('voucher').currentSize)
  cacheData.SetCacheData('voucher', PageNum, cacheData.GetCacheData('voucher').currentSize, findFrom)
}

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.Id && { Id: findFrom.Id }),
    ...(findFrom.TicketName && { TicketName: findFrom.TicketName }),
    ...(findFrom.Type !== '~' && { Type: findFrom.Type }),
    ...(findFrom.Flag !== '~' && { Flag: findFrom.Flag }),
  }

  GetData(params).then((res: any) => {
    if (res.succeeded) {
      dataList.list = res.data.items
      total.value = res.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`获取数据失败。${res.errors}`)
      loading.value = false
    }
  })
}
// 调整代金券状态
function ChangeDataType(row: any) {
  const params = {
    id: row.id,
    flag: row.flag,
  }
  patchListType(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('操作成功')
      GetDataList(cacheData.GetCacheData('voucher').currentPage, cacheData.GetCacheData('voucher').currentSize)
    }
    else {
      ElMessage.error('修改失败')
      GetDataList(cacheData.GetCacheData('voucher').currentPage, cacheData.GetCacheData('voucher').currentSize)
    }
  })
}

// 配置背景
const dialogFormVisible = ref(false)
const bgUrlId = ref('')
function handleBgUrlChange(id: string) {
  GetBgUrl({ id }).then((res) => {
    dataList.urlList = res.data.bgpicList
    bgUrlList.value = res.data.bgpicList.map((item: any) => {
      return item.picUrl.slice(22)
    })
  })
  bgUrlId.value = id
  dialogFormVisible.value = true
}

function BackUrlDeploy() {
  const updatedBgUrlList = bgUrlList.value.map(url => imgDomain + url)

  interface Item { id?: number, picUrl: string }
  const finalArray: Item[] = []

  dataList.urlList.forEach((item: any) => {
    const index = bgUrlList.value.findIndex(url => url === item.picUrl.slice(22))

    if (index !== -1) {
      finalArray.push({
        id: item.id,
        picUrl: imgDomain + bgUrlList.value[index],
      })
    }
  })

  updatedBgUrlList.forEach((url) => {
    const exists = finalArray.some(item => item.picUrl === url)

    if (!exists) {
      finalArray.push({
        id: 0,
        picUrl: url,
      })
    }
  })

  const params = {
    couponId: bgUrlId.value,
    bgpicList: finalArray,
  }
  PostAlterBgUrl(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('操作成功')
      dialogFormVisible.value = false
    }
    else {
      ElMessage.error(`修改失败${res.errors}`)
    }
  })
}

// 新增
function AddCoupon() {
  router.push({
    name: 'voucherDetail',
  })
}

// 发送记录
function Operate(id: number) {
  router.push({
    name: 'voucherOperate',
    query: {
      id,
    },
  })
}

// 编辑
function Redact(id: number) {
  router.push({
    name: 'voucherDetail',
    query: {
      id,
    },
  })
}

// 编辑
function GrantVoucher(id: number) {
  router.push({
    name: 'voucherSendcoupon',
    query: {
      ticketId: id,
    },
  })
}

// 复制
function Copy(id: number) {
  ElMessageBox.confirm(
    '是否复制该代金券',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      PostCopy(id).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('复制成功。')
          GetDataList(cacheData.GetCacheData('voucher').currentPage, cacheData.GetCacheData('voucher').currentSize)
          ElMessageBox.confirm(
            '是否编辑新增的代金券？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            },
          )
            .then(() => {
              router.push({
                name: 'voucherDetail',
                query: {
                  id: res.data,
                },
              })
            })
        }
        else {
          ElMessage.error(`复制失败。${res.errors}`)
        }
      })
    })
}

// 关联商品
function connectCommodity(row: any) {
  router.push({
    name: 'voucherProducts',
    query: {
      id: row.id,
    },
  })
}

// 删除
function DeleteData(id: number) {
  deleteCoupon(id).then((res: any) => {
    if (res.succeeded) {
      dataList.list = dataList.list.filter((item: any) => item.id !== id)
      ElMessage.success('删除成功')
    }
    else {
      ElMessage.error(`删除失败${res.errors}`)
    }
  })
}

// 批量更新
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const couponIdList = ref([])
function handleSelectionChange(val: any) {
  couponIdList.value = val.map((item: any) => {
    return item.id
  })
}
const updateTime = ref('')
const updateDialog = ref(false)
function Update() {
  updateTime.value = ''
  updateDialog.value = true
}
function UpdateTime() {
  const params = {
    couponIdList: couponIdList.value,
    expiredTime: updateTime.value,
  }
  if (params.expiredTime === '') {
    ElMessage.error('请选择过期时间')
    return
  }
  else if (params.couponIdList.length === 0) {
    ElMessage.error('请在表格上选择要修改的卡券')
    return
  }
  PostUpdateTime(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('修改成功')
      updateDialog.value = false
      GetDataList(cacheData.GetCacheData('voucher').currentPage, cacheData.GetCacheData('voucher').currentSize)
    }
    else {
      ElMessage.error(`修改失败。${res.errors}`)
    }
  })
}

async function ExportExcel() {
  const params = {
    ...(findFrom.Id && { Id: findFrom.Id }),
    ...(findFrom.TicketName && { TicketName: findFrom.TicketName }),
    ...(findFrom.Type !== '~' && { Type: findFrom.Type }),
    ...(findFrom.Time.length !== 0 && { StartTime: findFrom.Time[0], EndTime: findFrom.Time[1] }),
  }
  try {
    const response: any = await GetExcelData(params)
    // console.log(response)

    const a = document.createElement('a')
    const binaryData = []
    binaryData.push(response)
    a.href = window.URL.createObjectURL(
      new Blob(binaryData, {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=UTF-8',
      }),
    )
    a.download = (storage.local.get('fileName') as string)
    storage.local.remove('fileName')
    a.click()
    URL.revokeObjectURL(a.href)
  }
  catch (error) {
    // 请求失败处理
    console.error(error)
  }
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('voucher', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('voucher').currentSize)
  cacheData.SetCacheData('voucher', val, cacheData.GetCacheData('voucher').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('voucher').currentPage || 1
})

onMounted(() => {
  GetDataList(cacheData.GetCacheData('voucher').currentPage, cacheData.GetCacheData('voucher').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="券ID">
                <el-input v-model="findFrom.Id" style="width: 240px;" placeholder="请输入代金券ID" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="名称">
                <el-input v-model="findFrom.TicketName" style="width: 240px;" placeholder="请输入代金券名称" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="类型">
                <el-select v-model="findFrom.Type" placeholder="请选择代金券类型" style="width: 240px;">
                  <el-option label="全部" value="~" />
                  <el-option v-for="item in voucherType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="findFrom.Flag" placeholder="请选择代金券类型" style="width: 240px;">
                  <el-option label="全部" value="~" />
                  <el-option v-for="item in voucherFlag" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5" style="display: flex; justify-content: space-between;">
        <el-button @click="Update">
          批量更新过期时间
        </el-button>
        <div>
          <span>发券时间：</span>
          <el-date-picker
            v-model="findFrom.Time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="margin-right: 5px;"
          />
          <el-button type="success" @click="ExportExcel">
            导出券数据
          </el-button>
          <el-button type="success" @click="AddCoupon">
            新增卡券
          </el-button>
        </div>
      </div>
      <ElTable ref="multipleTableRef" v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" label="图标" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.picUrl" />
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="name" label="名称" width="350" show-overflow-tooltip />
        <el-table-column align="center" prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.type === 1 ? '赠品券'
                : scope.row.type === 2 ? '奖品券'
                  : scope.row.type === 3 ? '满减券' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="price" label="面值" width="100" />
        <el-table-column header-align="center" prop="intro" label="分享描述" width="340" />
        <el-table-column align="center" prop="endTime" label="失效时间" width="220" />
        <el-table-column align="center" prop="flag" label="状态" fixed="right" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.flag"
              :active-value="1"
              :inactive-value="0"
              @click="ChangeDataType(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="370">
          <template #default="scope">
            <div style="line-height: 42px;">
              <el-button type="success" @click="Copy(scope.row.id)">
                复制
              </el-button>
              <el-button type="success" @click="GrantVoucher(scope.row.id)">
                发放卡券
              </el-button>
              <el-button type="primary" @click="Redact(scope.row.id)">
                编辑
              </el-button>
              <el-popconfirm title="你确定要删除吗?" @confirm="DeleteData(scope.row.id)">
                <template #reference>
                  <el-button type="danger">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
              <el-button type="info" @click="Operate(scope.row.id)">
                发送记录
              </el-button>
              <el-button type="info" @click="handleBgUrlChange(scope.row.id)">
                领券背景
              </el-button>
              <el-button v-if="scope.row.relateProduct === 1" color="#626aef" type="success" @click="connectCommodity(scope.row)">
                关联商品
              </el-button>
            </div>
          </template>
        </el-table-column>
      </ElTable>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('voucher').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-dialog v-model="dialogFormVisible" title="配置领券页背景" width="800" :destroy-on-close="true">
        <ImagesUpload :width="180" :ext="['jpg', 'png']" :size="5" :max="10" :url="bgUrlList" />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="BackUrlDeploy">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="updateDialog" title="批量更新券过期时间" width="450" :destroy-on-close="true" center>
        <div style="margin: 15px 0; text-align: center;">
          <el-date-picker
            v-model="updateTime"
            type="datetime"
            placeholder="请选择失效日期和时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="updateDialog = false">
              取消
            </el-button>
            <el-button type="primary" @click="UpdateTime">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;
  }
}

.el-form-item {
  margin-bottom: 0;
}
</style>
